use std::fmt::Debug;

use serde::Serialize;
use serde_json::{json, Value};

use super::error::ErrorCode;


#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct WebRet<D> {
    pub code: i32,
    pub msg: String,
    pub data: Option<D>,
}

#[allow(dead_code)]
impl<D: Debug + Serialize> WebRet<D> {
    pub fn get_code(&self) -> i32 {
        self.code
    }
    pub fn get_msg(&self) -> String {
        self.msg.clone()
    }
    pub fn success(data: Option<D>) -> WebRet<D> {
        WebRet {
            code: ErrorCode::SUCCESS.get_code(),
            msg: ErrorCode::SUCCESS.get_desc().to_string(),
            data: data,
        }
    }
    pub fn success_with_msg(msg: String, data: Option<D>) -> WebRet<D> {
        WebRet {
            code: ErrorCode::SUCCESS.get_code(),
            msg: msg,
            data: data,
        }
    }
    pub fn error(code: i32, msg: String) -> WebRet<D> {
        WebRet {
            code: code,
            msg: msg,
            data: None,
        }
    }
    pub fn error_with_data(code: i32, msg: String, data: D) -> WebRet<D> {
        WebRet {
            code: code,
            msg: msg,
            data: Some(data),
        }
    }
    pub fn append_msg(mut self, append_msg: String) -> WebRet<D> {
        let cur_msg = self.get_msg();
        self.msg = format!("{}:{}", cur_msg, append_msg);
        self
    }
    pub fn reset_msg(mut self, new_msg: String) -> WebRet<D> {
        self.msg = new_msg;
        self
    }
    pub fn to_json(self) -> Value {
        json!(self)
    }
}

#[derive(Debug, Serialize)]
pub struct EmptyData;
